<template>
	<view class="record-wrap">
		<!-- 菜单（详情模式下不展示） -->
		<view class="menu-wrap" v-if="!showDetail">
			<view class="menu-item" :class="{ active: activeMenu === 'offline' }" @click="switchMenu('offline')">线上
			</view>
			<view class="menu-item" :class="{ active: activeMenu === 'online' }" @click="switchMenu('online')">线下</view>
		</view>

		<!-- 记录列表 -->
		<view class="record-list" v-if="!showDetail && recordList.length > 0">
			<view class="record-item" v-for="(item, index) in recordList" :key="item.id">
				<view class="record-time">
					{{ activeMenu === 'offline' ? formatDate(item.createdTime) : formatDate(item.createTime) }}
				</view>

				<!-- 线上病历下载 -->
				<view class="record-download" v-if="activeMenu === 'offline' && item.caFileUrl"
					@click="downloadFile(item)">
					<image class="download-icon"
						src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/mine/ic_mine_recipe.png" />
					<text>{{ item.createTime }}</text>
					<text>{{ item.patientName }}</text>
					<text class="download-text">查看电子病历</text>
				</view>

				<!-- 线下病历链接 -->
				<view class="record-link" v-if="activeMenu === 'online'" @click="openOnlineRecord(item, index)">
					<image class="link-icon"
						src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/mine/ic_mine_recipe.png" />
					<view class="link-text">
						<text>{{ item.name || '未知姓名' }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="!showDetail && recordList.length === 0">
			<text>暂无记录</text>
		</view>

		<!-- 详情页 -->
		<view class="detail-view" v-if="showDetail">
			<view class="detail-header">
				<text class="back-btn" @click="closeDetail">← 返回</text>
				<text class="detail-title">病历详情</text>
			</view>
			<view class="detail-content">
				<view><text>姓名：</text>{{ currentRecord.name || '未知' }}</view>
				<view><text>性别：</text>{{ currentRecord.sex || '未知' }}</view>
				<view><text>年龄：</text>{{ currentRecord.age || '未知' }}{{ currentRecord.ageUnit || '' }}</view>
				<view><text>身份证号：</text>{{ currentRecord.identifyId || '无' }}</view>
				<view><text>出生日期：</text>{{ currentRecord.birthday || '无' }}</view>
				<view><text>联系电话：</text>{{ currentRecord.phoneNumber || '无' }}</view>
				<view><text>就诊时间：</text>{{ currentRecord.createTime || '未知' }}</view>
				<view><text>门诊号：</text>{{ currentRecord.patientNumber || '无' }}</view>
				<view><text>号别：</text>{{ currentRecord.type || '无' }}</view>
				<view><text>科室：</text>{{ currentRecord.department || '无' }}</view>
				<view><text>医生：</text>{{ currentRecord.doctor || '无' }}</view>
				<view><text>诊断：</text>{{ currentRecord.clinicDiagnosis || '无' }}</view>
				<view><text>过敏史：</text>{{ currentRecord.allergy || '无' }}</view>
				<view><text>病历信息：</text>{{ currentRecord.content || '无' }}</view>
			</view>

			<text>西药处方：</text>
			<view v-if="currentRecord.westernMedicine.length > 0">
				<view v-for="(med, index) in currentRecord.westernMedicine" :key="index">
					<text>---------------------------------------------</text>
					<text>{{ index + 1 }}. {{ med.name || '未知药品' }}</text>
					<text>处方号 : {{ med.prescriptionId || "" }}</text>
					<text>频次 : {{ med.frequency || "" }}</text>
					<text>开药日期 : {{ med.createTime || "" }}</text>
					<text>医嘱 : {{ med.doctorAdvice || "" }}</text>
					<text>用量 : {{ med.dosage || "" }}</text>
					<text>数量 : {{ med.count || "" }}</text>
					<text>单位 : {{ med.unit || "" }}</text>
					<text>---------------------------------------------</text>
				</view>
			</view>
			<view v-else>无</view>

			<text>中药处方：</text>
			<view v-if="currentRecord.chineseMedicine.length > 0">
				<view v-for="(med, index) in currentRecord.chineseMedine" :key="index">
					<text>---------------------------------------------</text>
					<text>{{ index + 1 }}. {{ med.name || '未知药品' }}</text>
					<text>处方号 : {{ med.prescriptionId || "" }}</text>
					<text>开药日期 : {{ med.prescriptionId || "" }}</text>
					<text>频次 : {{ med.prescriptionId || "" }}</text>
					<text>医嘱信息 : {{ med.prescriptionId || "" }}</text>
					<text>中药付数 : {{ med.prescriptionId || "" }}</text>
					<text>煎法 : {{ med.prescriptionId || "" }}</text>
					<text>给药途径 : {{ med.prescriptionId || "" }}</text>
					<text>---------------------------------------------</text>
				</view>
			</view>
			<view v-else>无</view>
		</view>
	</view>
</template>

<script>
	import request from '@/api/request'
	import {
		userInfo
	} from '@/utils/token.js'

	export default {
		data() {
			return {
				recordList: [],
				activeMenu: 'offline',
				pageNo: 1,
				pageSize: 10,
				loading: false,
				patientId: '',
				showDetail: false,
				currentRecord: {}, // 当前选中记录
				id: null
			}
		},
		onLoad(options) {
			this.id = options.id
			const user = userInfo.get()
			if (user) {
				this.patientId = user.id
			}
			this.getRecordList()
		},
		methods: {
			switchMenu(type) {
				this.activeMenu = type
				this.pageNo = 1
				this.recordList = []
				this.getRecordList()
			},
			// 打开线下病历详情
			openOnlineRecord(item, index) {
				console.log("item", item)
				console.log("index", index)
				this.currentRecord = item
				this.showDetail = true
			},
			// 返回列表
			closeDetail() {
				this.showDetail = false
				this.currentRecord = {}
			},
			async getRecordList() {
				if (this.loading) return
				this.loading = true
				try {
					if (this.activeMenu === 'offline') {
						const res = await request.globalRequest(
							'/aos/client/patientmedicalrecord/patientMedicalRecordOnlineListOnDoctor', 'GET', {
								params: {
									id: this.id,
									pageNo: this.pageNo,
									pageSize: this.pageSize
								}
							})
						if (res.code === 200) {
							this.recordList = [...this.recordList, ...res.result.records]
						} else {
							uni.showToast({
								title: res.message || '获取记录失败',
								icon: 'none'
							})
						}
						console.log(this.recordList);
					} else {
						const res = await request.globalRequest('/aos/health/listHisMedicalRecordOnDoctor', 'GET', {
							params: {
								id: this.id
							}
						})
						if (res.code === 200) {
							this.recordList = [...res.result]
							console.table(this.recordList)
						} else {
							uni.showToast({
								title: res.message || '获取记录失败',
								icon: 'none'
							})
						}
					}
				} catch (error) {
					console.error(error)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},
			formatDate(date) {
				if (!date) return ''
				return date.substring(0, 10)
			},
			downloadFile(item) {
				console.log("item", item)
				if (!item.caFileUrl) {
					uni.showToast({
						title: '暂无电子病历文件',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '下载中...'
				})
				uni.downloadFile({
					url: item.caFileUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.hideLoading()
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (saveRes) => {
									uni.showToast({
										title: '下载成功',
										icon: 'success'
									})
									uni.openDocument({
										filePath: saveRes.savedFilePath,
										success: () => {
											console.log('打开文档成功')
										},
										fail: () => {
											uni.showToast({
												title: '文件打开失败',
												icon: 'none'
											})
										}
									})
								},
								fail: () => {
									uni.showToast({
										title: '文件保存失败',
										icon: 'none'
									})
								}
							})
						}
					},
					fail: () => {
						uni.hideLoading()
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						})
					}
				})
			}
		},
		onPullDownRefresh() {
			this.pageNo = 1
			this.recordList = []
			this.getRecordList().then(() => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			if (!this.loading) {
				this.pageNo++
				this.getRecordList()
			}
		}
	}
</script>

<style lang="less" scoped>
	.record-wrap {
		min-height: 100vh;
		background: #f5f5f5;

		.menu-wrap {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20rpx 0;
			background: #fff;
			border-bottom: 1rpx solid #eee;

			.menu-item {
				padding: 10rpx 40rpx;
				margin: 0 20rpx;
				font-size: 28rpx;
				color: #666;
				position: relative;

				&.active {
					color: #2b9939;
					font-weight: 500;

					&::after {
						content: '';
						position: absolute;
						bottom: -4rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 40rpx;
						height: 4rpx;
						background: #2b9939;
						border-radius: 2rpx;
					}
				}
			}
		}

		.record-list {
			padding: 20rpx;

			.record-item {
				background: #fff;
				border-radius: 12rpx;
				padding: 30rpx;
				margin-bottom: 20rpx;

				.record-time {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 16rpx;
				}

				.record-download,
				.record-link {
					display: flex;
					align-items: center;
					padding: 16rpx 0;

					.download-icon,
					.link-icon {
						width: 32rpx;
						height: 32rpx;
						margin-right: 8rpx;
					}

					.download-text,
					.link-text {
						font-size: 28rpx;
						color: #2b9939;
					}
				}
			}
		}

		.empty-state {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 100rpx 0;
			color: #999;
			font-size: 28rpx;
		}

		.detail-view {
			padding: 30rpx;
			background-color: #fff;
			min-height: 100vh;

			.detail-header {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.back-btn {
					font-size: 28rpx;
					color: #2b9939;
					margin-right: 20rpx;
				}

				.detail-title {
					font-size: 32rpx;
					font-weight: bold;
				}
			}

			.detail-content {
				font-size: 28rpx;
				color: #333;
				line-height: 48rpx;

				view {
					margin-bottom: 12rpx;
				}
			}
		}
	}
</style>